#!/bin/bash
#设置变量，url为你需要检测的目标网站的网址（IP或域名）
hostUrl=https://xxx.com/xx
localUrl=http://localhost:80/xx

mkdir -p /home/ec2-user/watch/log
rm -rf /home/ec2-user/watch/log/http.log
rm -rf /home/ec2-user/watch/log/http-error.log

#定义函数check_http：
#使用curl命令检查http服务器的状态
#-m设置curl不管访问成功或失败，最大消耗的时间为5秒，5秒连接服务为相应则视为无法连接
#-s设置静默连接，不显示连接时的连接速度、时间消耗等信息
#-o将curl下载的页面内容导出到/dev/null(默认会在屏幕显示页面内容)
#-w设置curl命令需要显示的内容%{http_code}，指定curl返回服务器的状态码
check_http(){
lb_status_code=$(curl -m 5 -o /dev/null -w %{http_code} -s ${hostUrl})
localhost_status_code=$(curl -m 5 -o /dev/null -w %{http_code} -s ${localUrl})
}

while :
do
       check_http
       date=$(date +%Y-%m-%d-%H:%M:%S)
       if [[ ${lb_status_code} -ne 200 ]] || [[ ${localhost_status_code} -ne 200 ]];then
              errMsg="time:$date, $hostUrl or $localUrl error, $hostUrl code: ${lb_status_code}. $localUrl code: ${localhost_status_code}. Emper restart pm2 node server. Please check."
              echo ${errMsg} >> /home/ec2-user/watch/log/http-error.log
              curl -H "Content-Type:application/json" -X POST -d '{"msgtype":"text",text:{"content": "'"${errMsg}"'"},at:{isAtAll:false,atMobiles:[phones]}}' 'https://oapi.dingtalk.com/robot/send?access_token=token'
              sh /home/ec2-user/uptrade-home/pm2-deploy.sh prod
       else
              okMsg="time:$date $hostUrl ok, code: ${lb_status_code}. $localUrl ok, code: ${localhost_status_code}."
              echo ${okMsg} >> /home/ec2-user/watch/log/http.log
       fi
       sleep 5
done